import 'package:flutter/material.dart';
import 'package:talk/utils/toast_utils.dart';

import '../../api/ShareApi.dart';
import '../../api/dio/DioClient.dart';
import '../../commponets/ItemView.dart';
import '../../home/AppLocale.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../my/model/UserModel.dart';

class DeviceShareAddPage extends StatefulWidget {
  const DeviceShareAddPage({
    super.key,
    this.deviceId,
    this.userId,
  });

  final int? deviceId;
  final int? userId;

  @override
  State<DeviceShareAddPage> createState() => _DeviceShareAddPageState();
}

class _DeviceShareAddPageState extends State<DeviceShareAddPage> {
  final ShareApi _shareApi = ShareApi();
  late int _deviceId;
  late int _userId;
  final TextEditingController _searchController = TextEditingController();
  // 使用Map列表存储用户数据，包含必要字段和选中状态
  List<Map<String, dynamic>> _users = [];
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId ?? 0;
    _userId = widget.userId ?? 0;

    // 初始化空数据，不加载任何用户信息
    _users = [];
  }

  // 调用API搜索用户
  Future<void> _searchPersons() async {
    if (_searchController.text.trim().isEmpty) {
      Toast.show("请输入搜索关键词");
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final response = await _shareApi.getUserPhone(_searchController.text.trim());


      if (response.code == 200 && response.data != null) {
        // 处理返回的用户数据，添加选中状态字段
        List<Map<String, dynamic>> userList =
        (response.data as List).cast<Map<String, dynamic>>();

        // 为每个用户添加isSelected字段
        for (var user in userList) {
          user['isSelected'] = false;
        }

        setState(() {
          _users = userList;
        });
      } else {
        Toast.show(response.getMsg ?? "搜索用户失败");
        setState(() {
          _users = [];
        });
      }
    } catch (e) {
      Toast.show("搜索异常: ${e.toString()}");
      setState(() {
        _users = [];
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 切换用户选择状态
  void _toggleSelection(int index) {
    setState(() {
      _users[index]['isSelected'] = !_users[index]['isSelected'];
    });
  }

  // 确认分享
  Future<void> _confirmShare(BuildContext context) async {
    // 获取选中的人员
    final selectedUsers = _users
        .where((user) => user['isSelected'] == true)
        .toList();

    if (selectedUsers.isEmpty) {
      Toast.show("请选择要分享的人员");
      return;
    }

    setState(() {
      _isLoading = true;
    });


    try {
      // 调用分享API，假设ShareApi有shareDevice方法
      // 提取选中用户的ID列表
      List<int> userIds = selectedUsers.map((user) => user['userId'] as int).toList();

      final toUpdate = {
        "userId": _userId,
        "deviceId": _deviceId,
        "toList": userIds,
      };

      final response = await _shareApi.deviceShare(toUpdate);

      if (response.code == 200) {
        Toast.show("分享成功");
        // Navigator.pop(context, true); // 返回上一页并刷新数据
        // 等待更新操作完成
        // await _updateDataSelect();
        Toast.show(response.getMsg ?? "分享失败");
        // 只有更新成功后才返回（可选，根据需求调整）
        Navigator.maybePop(context);
      } else {
        Toast.show(response.msg ?? "分享失败");
      }
    } catch (e) {
      Toast.show("分享异常: ${e.toString()}");
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: AppLocale.text('d_shebeifenxiang'),
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
      ),
      body: Column(
        children: [
          // 搜索框
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8.0),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 12.0),
                      child: TextField(
                        controller: _searchController,
                        decoration: InputDecoration(
                          hintText: AppLocale.text('d_shurshoujihaohuoyonghuming'),
                          hintStyle: const TextStyle(
                            color: Colors.black54,
                            fontSize: 14,
                          ),
                          border: InputBorder.none,
                          icon: Icon(
                            Icons.search,
                            color: Colors.grey,
                          ),
                        ),
                        textInputAction: TextInputAction.search,
                        onSubmitted: (_) => _searchPersons(),
                      ),
                    ),
                  ),
                  TextButton(
                    onPressed: _searchPersons,
                    child:
                    Text(
                      AppLocale.text('d_sousuo'),
                      style: TextStyle(
                        color: Colors.blue,
                        fontWeight: FontWeight.bold,
                        fontSize: 16
                      ),
                    ),

                  ),
                  const SizedBox(width: 7,),
                ],
              ),
            ),
          ),

          const SizedBox(height: 20),

          // 人员列表标题
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.0),
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(
                AppLocale.text('d_kexuanrenyuan'),
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),

          const SizedBox(height: 10),

          // 人员列表
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : _users.isEmpty
                ? Center(child: Text(AppLocale.text('d_shruuguanjianchi')))
                : ListView.builder(
              padding: const EdgeInsets.symmetric(horizontal: 10),
              itemCount: _users.length,
              itemBuilder: (context, index) {
                // 获取当前项数据
                final user = _users[index];
                // 解析用户信息（处理null情况）
                // final userMap = user['toUser'] as Map<String, dynamic>?;
                final userData = UserModel.fromJson(user);
                // // 直接获取头像和昵称（带默认值）
                final avatarUrl = '${DioClient.baseUrl}${userData!.avatar}' ?? 'http://43.139.39.5:82/pho/face/default.jpg';
                final userName = userData.userName ?? AppLocale.text('d_weizhiyonghu');

                final phone = userData.phonenumber ?? '';

                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 4.0),
                  child: ItemView(
                    width: 400,
                    height: 70,
                    leftPadding: 10,
                    rightPadding: 20,
                    leftWidget: Row(
                      children: [
                        const SizedBox(width: 10),
                        // 头像
                        CircleAvatar(
                          radius: 18,
                          backgroundColor: Colors.grey[200],
                          child: ClipOval(
                            child: Image.network(
                              avatarUrl,
                              width: 45,
                              height: 45,
                              fit: BoxFit.cover,
                              errorBuilder: (context, error, stackTrace) =>
                                  Image.network(
                                    'http://43.139.39.5:82/pho/face/default.jpg',
                                    width: 45,
                                    height: 45,
                                    fit: BoxFit.cover,
                                  ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 10),
                        // 名称和角色
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              userName,
                              style: const TextStyle(
                                fontSize: 15,
                                // fontWeight: FontWeight.w500,
                              ),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              phone,
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey[600],
                              ),
                            ),
                            const SizedBox(height: 3),
                          ],
                        ),
                      ],
                    ),
                    rightWidget: Icon(
                      user['isSelected']
                          ? Icons.check_circle
                          : Icons.circle_outlined,
                      color: user['isSelected'] ? Colors.blue : Colors.grey,
                    ),
                    borderRadius: 8,
                    backgroundColor: Colors.white,
                    onTap: () => _toggleSelection(index),
                  ),
                );
              },
            ),
          ),

          // 底部确认按钮
          Padding(
            padding: const EdgeInsets.all(20.0),
            child: SizedBox(
              width: double.infinity,
              height: 50,
              child: ElevatedButton(
                onPressed: () => _confirmShare(context),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: Text(
                  AppLocale.text('d_querenfenxiang'),
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

